﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

using LowLevelGraphics;
namespace ImageRecognition2
{
    /// <summary>
    /// This is used to get specifiy win32 operations done.
    /// </summary>
    public class Win32Helpers
    {
        private const int MAXTITLE = 255;

        private static ArrayList mTitlesList;

        /// <summary>
        /// Enumerates the windows.
        /// </summary>
        /// <param name="hWnd">The h WND.</param>
        /// <param name="lParam">The l param.</param>
        /// <returns></returns>
        private static bool EnumWindowsProc(IntPtr hWnd, int lParam)
        {
            string title = GetWindowText(hWnd);
            mTitlesList.Add(title);
            return true;
        }

        /// <summary>
        /// Returns the caption of a windows by given HWND identifier.
        /// </summary>
        public static string GetWindowText(IntPtr hWnd)
        {
            StringBuilder title = new StringBuilder(MAXTITLE);
            int titleLength = CGraphics.GetWindowText(hWnd, title, title.Capacity + 1);
            title.Length = titleLength;

            return title.ToString();
        }

        [DllImport("user32.dll")]
        public static extern bool FlashWindow(IntPtr hwnd, bool bInvert);

        public bool FlashSelectedhWindow(IntPtr hwnd, bool _bInvert)
        {
            return FlashWindow(hwnd, _bInvert);
        }

        /// <summary>
        /// Returns the caption of all desktop windows.
        /// </summary>
        public static string[] GetDesktopWindowsCaptions()
        {            
            mTitlesList = new ArrayList();
            CGraphics.EnumDesktopWindowsDelegate enumfunc = new CGraphics.EnumDesktopWindowsDelegate(EnumWindowsProc);
            IntPtr hDesktop = IntPtr.Zero; // current desktop
            bool success = CGraphics.EnumDesktopWindows(hDesktop, enumfunc, IntPtr.Zero);

            if (success)
            {
                // Copy the result to string array
                string[] titles = new string[mTitlesList.Count];
                mTitlesList.CopyTo(titles);
                return titles;
            }
            else
            {
                // Get the last Win32 error code
                int errorCode = Marshal.GetLastWin32Error();

                string errorMessage = String.Format(
                "EnumDesktopWindows failed with code {0}.", errorCode);
                throw new Exception(errorMessage);
            }
        }
    }
}
